<?php
/**
 * Created by PhpStorm.
 * User: 王松
 * Time: 2017/6/5 15:25
 */

namespace App\Http\Controllers\Manage;

use App\Http\Controllers\ApiController;
use App\Http\Requests\ComplaintStoreRequest;
use App\Http\Requests\ComplaintUpdateRequest;
use App\Models\MedicalComplaint;
use App\Project\Filters\ComplaintFilter;
use App\Project\Transform;
use App\Transformers\ComplaintTransformer;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;

/**
 * 主诉控制器
 * Class ComplaintController
 * @package App\Http\Controllers\Manage
 */
class ComplaintController extends ApiController
{
    /**
     * 主诉存储 多次提交视为更新
     * @param \App\Http\Requests\ComplaintStoreRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(ComplaintStoreRequest $request)
    {
        $input = (new ComplaintFilter($request))->input();
        
        $result = MedicalComplaint::updateOrCreate(['record_id' => $input['record_id']], $input);

        return $this->response(['id' => $result['id']]);
    }

    /**
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function edit(Request $request)
    {

        $data = null;
        $id   = $request->get('id');

        if ($id > 0) {

            $data = MedicalComplaint::findOrFail($id);
        } elseif ($record_id = $request->get('record_id')) {

            $data = MedicalComplaint::where(['record_id' => $record_id])->first();
        } else {
            abort(400, '缺失主诉ID，或者病历ID');
        }

        if (empty($data)) {
            throw (new ModelNotFoundException())->setModel(MedicalComplaint::class);
        }

        return $this->item($data, new ComplaintTransformer());
    }

    /**
     * @param \App\Http\Requests\ComplaintUpdateRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(ComplaintUpdateRequest $request)
    {
        $where = [];

        if ($id = $request->input('id')) {
            $where['id'] = $id;
        } else {
            $where['record_id'] = $request->input('record_id');
        }

        $input = (new ComplaintFilter($request))->except(['id', 'record_id']);

        if(array_key_exists("weightchange",$input) and $input['weightchange']==0){
            $input['weightchangestatus']=0;
            $input['weightchangekg']=0;
        }
        if(array_key_exists("weightchangestatus",$input) and $input['weightchangestatus']==2){
            $input['weightchangekg']=0;
        }

        $input = (new Transform())->setArray($input)
                                  ->convertArrayToJson(['symptoms', 'blood_glucose', 'medication', 'cn_medication'])
                                  ->get();

        $result = MedicalComplaint::where($where)->update($input);

        return $this->responseForUpdate($result);
    }
}